// Pages/category/category.js
import {Category} from "./category_model.js";
var category = new Category;
Page({

  /**
   * 页面的初始数据
   */
  data: {
     currentTabIndex: 0,
     categoryProducts: '',
     categoryTypeArr: '',
     alreadyLoadDataStorage:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     this._onloadData();
  },
  _onloadData:function(){
     category.getCategoryData((res) => {
        this.setData({
           categoryTypeArr:res
        });
        //放在函数内防止异步的时间差
        var id = res[0].id;
        category.getProductsByCategory(id, (productList) => {
           var productObj = {
              products: productList,
              topImgUrl:res[0].img.url,
              title:res[0].name
           };
           this.setData({
              categoryProducts: productObj
           });
           this.data.alreadyLoadDataStorage[0] = productObj;
        })
     })
  },
   onChangeCategoryTab:function(event){
      var index = category.getDataSet(event, 'index');
      this.setData({
         'currentTabIndex': index
      });
      if(!this.data.alreadyLoadDataStorage[index]){
         var currentTabData = this.data.categoryTypeArr[index];
         var id = currentTabData.id;
         category.getProductsByCategory(id, (res) => {
            var productObj = {
               products: res,
               topImgUrl: currentTabData.img.url,
               title: currentTabData.name
            };
            this.setData({
               categoryProducts: productObj
            });
            this.data.alreadyLoadDataStorage[index] = productObj;
         })
      }else{
         this.setData({
            categoryProducts: this.data.alreadyLoadDataStorage[index],
         })
      }
   },
   onProductItemClick:function(event){
      var id = category.getDataSet(event, 'id');
      wx.navigateTo({
         url: '../product/product?id=' + id,
      })
   },
   onReady:function(){
      wx.setNavigationBarTitle({
         title: '商品分类'
      })
   }
  
})